package cn.kgc.shiroday03.controller;

import cn.hutool.captcha.LineCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/6/5
 * @Description: 生成验证码
 */
@Controller
@RequestMapping("captcha")
public class CaptchaController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 生成验证码
    @GetMapping("getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {

        LineCaptcha lineCaptcha = new LineCaptcha(110, 50, 4, 3);
        String code = lineCaptcha.getCode();
        String id = session.getId();

        //将验证码 存入 redis缓存中间件   key:value   code:code
        stringRedisTemplate.opsForValue().set(id,code,1, TimeUnit.MINUTES);

        // 将验证码写出到前端页面
        ServletOutputStream outputStream = response.getOutputStream();
        lineCaptcha.write(outputStream);
        outputStream.close();

    }

}
